package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.AdvertiseInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.hxsdk.PreferenceManager;
import com.xgkj.diyiketang.task.AdvertisementTask;
import com.xgkj.diyiketang.task.LoginTask;
import com.xgkj.diyiketang.task.ThirdLoginTask;
import com.xgkj.diyiketang.util.AppMetaData;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.JpushUtil;
import com.xgkj.diyiketang.util.PalLog;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class LoadingActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = "LoadingActivity";
    private int mTaskId = -1;
    private Context mContext;
    private String loginName;
    private String loginPsw;
    Intent intent;
    private String appVersion;
    private String currentVersion;
    private String openidString;
    private String nicknameString;
    private String thirdIconUrl;
    private int openTaskID = -1;
    private Intent extraIntent;
    private int thirdType = 2;
    private TextView tiaoguo;
    private TextView excess_time;
    private int adtaskId = -1;
    private ImageView adImgeView;
    private List<AdvertiseInfo> adList = new ArrayList<AdvertiseInfo>();
    private Mycount mycount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);
        mContext = this;
         intent = new Intent(mContext, LoginActivity.class);
//        intent = new Intent(mContext, MainActivity.class);
        extraIntent = getIntent();
        if (extraIntent != null) {
            intent.putExtras(extraIntent);
        }
        loginName = EatShowSetting.getInstance(mContext).getLoginName();
        loginPsw = EatShowSetting.getInstance(mContext).getLoginPsw();
        openidString = EatShowSetting.getInstance(mContext).getThirdOpenid();
        nicknameString = EatShowSetting.getInstance(mContext).getThirdNickname();
        thirdIconUrl = EatShowSetting.getInstance(mContext).getThirdLogo();
        appVersion = EatShowSetting.getInstance(mContext).getAppVersion();
        thirdType = EatShowSetting.getInstance(mContext).getThirdType();
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            currentVersion = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        tiaoguo = (TextView) findViewById(R.id.tiaoguo);
        tiaoguo.setOnClickListener(this);
        excess_time = (TextView) findViewById(R.id.excess_time);
        adImgeView = (ImageView) findViewById(R.id.ad_img);

        getAdvertise();

        mycount = new Mycount(4000, 1000);
        mycount.start();
//        new Handler().postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                //进引导页
//                if (TextUtils.isEmpty(appVersion) || !appVersion.equals(currentVersion)){
//                    intent = new Intent(mContext,GudiePageActivity.class);
//                    startActivity(intent);
//                    finish();
//                }else {
//                    if (!TextUtils.isEmpty(loginName)
//                            && !TextUtils.isEmpty(loginPsw)) {
//                        startTask();
//                    } else if (!TextUtils.isEmpty(openidString) && !TextUtils.isEmpty(nicknameString) && !TextUtils.isEmpty(thirdIconUrl) && thirdType != -1) {
//                        thirdLoginTask();
//                    }else {
//                        finish();
//                        startActivity(intent);
//                    }
//                }
//            }
//        }, 2000);
    }

    private void getAdvertise() {
        AdvertisementTask adTask = new AdvertisementTask("1", "1");
        adTask.addListener(new LoadingTaskEventListener(mContext));
        adtaskId = getEatShowApp().getTaskManager().addTask(adTask);
    }


    class Mycount extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public Mycount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            excess_time.setText(millisUntilFinished / 1000 + "");
        }

        @Override
        public void onFinish() {
            excess_time.setText("");

        }
    }

    private void goGuide() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                //进引导页
                if (TextUtils.isEmpty(appVersion) || !appVersion.equals(currentVersion)) {
                    intent = new Intent(mContext, GudiePageActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    if (!TextUtils.isEmpty(loginName)
                            && !TextUtils.isEmpty(loginPsw)) {
                        startTask();
                    } else if (!TextUtils.isEmpty(openidString) && !TextUtils.isEmpty(nicknameString) && !TextUtils.isEmpty(thirdIconUrl) && thirdType != -1) {
                        thirdLoginTask();
                    } else {
                        finish();
                        startActivity(intent);
                    }
                }
            }
        }, 2000);
    }

    private void startTask() {
        if (mTaskId != -1) {
            return;
        }
        //LoginTask task = new LoginTask(loginName, loginPsw);
//        String areaname = EatShowSetting.getInstance(mContext).getFirstLocal();
//        String channel = AppMetaData.getMetaValue(mContext, "UMENG_CHANNEL");
        LoginTask task = new LoginTask(loginName, loginPsw);
        task.addListener(new LoadingTaskEventListener(mContext));
        mTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void thirdLoginTask() {
//        ThirdLoginTask open = new ThirdLoginTask(openidString,
//                nicknameString, thirdIconUrl);
//        open.addListener(new LoadingTaskEventListener(mContext));
//        openTaskID = getEatShowApp().getTaskManager().addTask(open);
//        String areaname = EatShowSetting.getInstance(mContext).getFirstLocal();
        String channel = AppMetaData.getMetaValue(mContext, "UMENG_CHANNEL");
        ThirdLoginTask open = new ThirdLoginTask(openidString,
                nicknameString, thirdIconUrl, channel, thirdType);
        open.addListener(new LoadingTaskEventListener(mContext));
        openTaskID = getEatShowApp().getTaskManager().addTask(open);
    }

    private void doHXLogin() {
        EMChatManager.getInstance().login(openidString, "123456", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        EMGroupManager.getInstance().loadAllGroups();
                        EMChatManager.getInstance().loadAllConversations();
                        PalLog.e("main", "登陆聊天服务器成功！");
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                PalLog.e("main", "登陆聊天服务器失败！");
            }
        });
    }


    class LoadingTaskEventListener extends ShowToastTaskEventListener {

        public LoadingTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            if (taskId == mTaskId) {
                mTaskId = -1;
                if (data != null) {
                    EatShowUserInfo userInfo = (EatShowUserInfo) data;
                    openidString = userInfo.getUserId();
                    thirdIconUrl = userInfo.getUserLogo();
                    getEatShowApp().setmUserInfo(userInfo);
                    doHXLogin();
                    if (userInfo.getTagList() != null && userInfo.getTagList().size() > 0) {
                        Set<String> tagList = new LinkedHashSet<String>(userInfo.getTagList());
                        JPushInterface.setAliasAndTags(getApplicationContext(), openidString, tagList, mAliasCallback);
                    }
                    PreferenceManager.getInstance().setCurrentUserAvatar(userInfo.getUserLogo());
                    PreferenceManager.getInstance().setCurrentUserNick(userInfo.getNickName());
                    Intent intentLogin = new Intent(mContext, MainActivity.class);
                    if (extraIntent != null) {
                        intentLogin.putExtras(extraIntent);
                    }
                    startActivity(intentLogin);
                    finish();
                }
            } else if (taskId == openTaskID) {
                openTaskID = -1;
                if (data != null) {
                    EatShowUserInfo esinfo = (EatShowUserInfo) data;
                    getEatShowApp().setmUserInfo(esinfo);
                    String chanelSchool = esinfo.getChanelSchoolName();
                    if (!TextUtils.isEmpty(chanelSchool)) {
                        getEatShowApp().getmUserInfo().setSchoolName(chanelSchool);
                    }
                    doHXLogin();
                    if (esinfo.getTagList() != null && esinfo.getTagList().size() > 0) {
                        Set<String> tagList = new LinkedHashSet<String>(esinfo.getTagList());
                        JPushInterface.setAliasAndTags(getApplicationContext(), esinfo.getUserId(), tagList, mAliasCallback);
                    }
                    PreferenceManager.getInstance().setCurrentUserAvatar(esinfo.getUserLogo());
                    PreferenceManager.getInstance().setCurrentUserNick(esinfo.getNickName());
                    Intent intent = new Intent(mContext, MainActivity.class);
                    if (extraIntent != null) {
                        intent.putExtras(extraIntent);
                    }
                    startActivity(intent);
                    finish();
                }
            } else if (taskId == adtaskId) {
                if (data != null) {
                    adList = (List<AdvertiseInfo>) data;

                    if (adList != null && adList.size() > 0) {
                        final String coverUrl = adList.get(0).getImageUrl();
                        ImageCache.getInstance(mContext).loadBitmapToView(adImgeView, coverUrl, null);
                        String type = adList.get(0).getType();
                        if (type != null && type.equals("1")) {
                            adImgeView.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
//                                        Intent adIntent = new Intent(Intent.ACTION_VIEW);
//                                        adIntent.setData(Uri.parse(adList.get(0).getUrl()));
//                                        mContext.startActivity(adIntent);
                                        String openUrl = adList.get(0).getUrl();
                                        Intent mIntent = new Intent(mContext, MainActivity.class);
                                        mIntent.putExtra("URL", openUrl);
                                        startActivity(mIntent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                        }
                    }
                    goGuide();
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            if (taskId == adtaskId) {
//                ImageCache.getInstance(mContext).loadBitmapToView(adImgeView, "http://imgsrc.baidu.com/forum/pic/item/9213b07eca80653846dc8fab97dda144ad348257.jpg", null);
                goGuide();
            } else {
                EatShowSetting.getInstance(mContext).setLoginName(null);
                EatShowSetting.getInstance(mContext).setLoginPsw(null);
                EatShowSetting.getInstance(mContext).setThirdOpenid(null);
                EatShowSetting.getInstance(mContext).setThirdNickname(null);
                EatShowSetting.getInstance(mContext).setThirdLogo(null);
                EatShowSetting.getInstance(mContext).setThirdType(-1);
                mTaskId = -1;
                openTaskID = -1;
                getEatShowApp().setmUserInfo(null);
                finish();
                startActivity(intent);
            }

        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, final String alias, final Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    PalLog.e(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    PalLog.e(TAG, logs);
                    if (JpushUtil.isConnected(getApplicationContext())) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JPushInterface.setAliasAndTags(getApplicationContext(), alias, tags, mAliasCallback);
                            }
                        }, 60 * 1000);
                    } else {
                        PalLog.e(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    PalLog.e(TAG, logs);
            }
        }
    };

    @Override
    public void onClick(View v) {/*
                                 * switch (v.getId()) { case R.id.test_1:
								 * test(); break; case R.id.test_2: init();
								 * break;
								 * 
								 * default: break; }
								 */
        switch (v.getId()) {
            case R.id.tiaoguo:
                if (TextUtils.isEmpty(appVersion) || !appVersion.equals(currentVersion)) {
                    intent = new Intent(mContext, GudiePageActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    if (!TextUtils.isEmpty(loginName)
                            && !TextUtils.isEmpty(loginPsw)) {
                        startTask();
                    } else if (!TextUtils.isEmpty(openidString) && !TextUtils.isEmpty(nicknameString) && !TextUtils.isEmpty(thirdIconUrl) && thirdType != -1) {
                        thirdLoginTask();
                    } else {
                        finish();
                        startActivity(intent);
                    }
                }
                break;
        }
    }

}
